package com.imooc.bilibili.file.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imooc.bilibili.domain.file.File;
import com.imooc.bilibili.file.IFileService;
import com.imooc.bilibili.mapper.file.FileMapper;
import com.imooc.bilibili.util.FastDFSUtil;
import com.imooc.bilibili.util.MD5Util;
import com.imooc.bilibili.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

/**
 * <p>
 * 文件表 服务实现类
 * </p>
 *
 * @author gcq
 * @since 2022-06-04
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements IFileService {

    @Autowired
    private FastDFSUtil fastDFSUtil;

    @Autowired
    private IFileService fileService;

    @Override
    public String uploadFileBySlices(MultipartFile file,
                                     String fileMd5,
                                     Integer sliceNo,
                                     Integer totalSliceNo) throws IOException {
        File dbFileMd5 = fileService.getOne(new QueryWrapper<File>().eq("md5", fileMd5));
        if(dbFileMd5 != null) {
            return dbFileMd5.getUrl();
        }

        String url = fastDFSUtil.uploadFileBySlices(file, fileMd5, sliceNo, totalSliceNo);
        if(StringUtils.isNotEmpty(url)) {
            File dbFile = new File();
            dbFile.setCreateTime(new Date());
            dbFile.setType(fastDFSUtil.getFileType(file));
            dbFile.setUrl(url);
            dbFile.setMd5(fileMd5);
            fileService.save(dbFile);
        }
        return url;
    }

    @Override
    public String getFileMd5(MultipartFile file) throws Exception {
        return MD5Util.getFileMD5(file);
    }

}
